<template>
  <div class="table-foreign-keys-panel-v2">
    <div class="max-w-6xl mx-auto">
      <!-- 头部 -->
      <div class="panel-header mb-6">
        <div class="flex items-center justify-between">
          <div>
            <h3 class="text-lg font-semibold text-gray-800">外键约束</h3>
            <p class="text-sm text-gray-500 mt-1">定义表之间的关联关系</p>
          </div>
          <el-button type="primary" @click="addForeignKey">
            <el-icon><Plus /></el-icon>
            添加外键
          </el-button>
        </div>
      </div>

      <!-- 外键列表 -->
      <div class="foreign-keys-list space-y-4">
        <div
          v-for="(fk, idx) in localForeignKeys"
          :key="fk._id || idx"
          class="fk-card bg-white rounded-lg shadow-sm border border-gray-200 p-4"
        >
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <div class="mb-3">
                <el-input
                  v-model="fk.name"
                  placeholder="外键名称"
                  class="w-64"
                  @change="handleChange"
                />
              </div>
              
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="text-sm text-gray-600 mb-1 block">本表列</label>
                  <el-select
                    v-model="fk.columns"
                    multiple
                    placeholder="选择列"
                    class="w-full"
                    @change="handleChange"
                  >
                    <el-option
                      v-for="col in columns"
                      :key="col.name"
                      :label="col.name"
                      :value="col.name"
                    />
                  </el-select>
                </div>
                
                <div>
                  <label class="text-sm text-gray-600 mb-1 block">引用表</label>
                  <el-input
                    v-model="fk.referenceTable"
                    placeholder="引用的表名"
                    @change="handleChange"
                  />
                </div>
                
                <div>
                  <label class="text-sm text-gray-600 mb-1 block">引用列</label>
                  <el-select
                    v-model="fk.referenceColumns"
                    multiple
                    placeholder="输入列名后回车"
                    filterable
                    allow-create
                    default-first-option
                    class="w-full"
                    @change="handleChange"
                  >
                    <el-option
                      v-for="col in fk.referenceColumns"
                      :key="col"
                      :label="col"
                      :value="col"
                    />
                  </el-select>
                </div>
                
                <div>
                  <label class="text-sm text-gray-600 mb-1 block">级联操作</label>
                  <div class="flex space-x-2">
                    <el-select
                      v-model="fk.updateRule"
                      placeholder="ON UPDATE"
                      size="small"
                      class="flex-1"
                      @change="handleChange"
                    >
                      <el-option label="CASCADE" value="CASCADE" />
                      <el-option label="RESTRICT" value="RESTRICT" />
                      <el-option label="SET NULL" value="SET NULL" />
                      <el-option label="NO ACTION" value="NO ACTION" />
                    </el-select>
                    <el-select
                      v-model="fk.deleteRule"
                      placeholder="ON DELETE"
                      size="small"
                      class="flex-1"
                      @change="handleChange"
                    >
                      <el-option label="CASCADE" value="CASCADE" />
                      <el-option label="RESTRICT" value="RESTRICT" />
                      <el-option label="SET NULL" value="SET NULL" />
                      <el-option label="NO ACTION" value="NO ACTION" />
                    </el-select>
                  </div>
                </div>
              </div>
            </div>
            
            <el-button
              type="danger"
              link
              @click="removeForeignKey(idx)"
              class="ml-4"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="localForeignKeys.length === 0" class="empty-state text-center py-12">
          <el-icon class="text-4xl text-gray-300 mb-2"><Link /></el-icon>
          <p class="text-gray-500">还没有添加任何外键约束</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Plus, Delete, Link } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const props = defineProps({
  foreignKeys: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    default: () => []
  },
  databaseType: {
    type: String,
    default: 'mysql'
  },
  connectionId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])

const localForeignKeys = ref([])

watch(() => props.foreignKeys, (newForeignKeys) => {
  localForeignKeys.value = newForeignKeys.map((fk, idx) => ({
    ...fk,
    _id: fk._id || `fk_${Date.now()}_${idx}`
  }))
}, { immediate: true, deep: true })

const addForeignKey = () => {
  const newForeignKey = {
    _id: `fk_${Date.now()}`,
    name: `fk_${localForeignKeys.value.length + 1}`,
    columns: [],
    referenceTable: '',
    referenceColumns: [],
    updateRule: 'CASCADE',
    deleteRule: 'RESTRICT'
  }
  localForeignKeys.value.push(newForeignKey)
  emitUpdate()
}

const removeForeignKey = (index) => {
  ElMessageBox.confirm('确定要删除这个外键约束吗？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localForeignKeys.value.splice(index, 1)
    emitUpdate()
  }).catch(() => {})
}

const handleChange = () => {
  emitUpdate()
}

const emitUpdate = () => {
  emit('update', localForeignKeys.value.map(fk => {
    const { _id, ...fkData } = fk
    return fkData
  }))
}
</script>

<style lang="scss" scoped>
.table-foreign-keys-panel-v2 {
  .fk-card {
    transition: all 0.3s;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }
}
</style> 